package utils
{
	import core.Model;
	
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.getTimer;

	public class EnterFrameTimer extends EventDispatcher
	{
		private var _currentCount:int;
		private var _running:Boolean;
		private var _repeatCount:int;
		private var _delay:int;
		private var _lastTime:int;
		private var _initTime:int;
		private var _isStop:Boolean;
		
		public function EnterFrameTimer(delay:Number,repeatCount:int=0)
		{
			_delay = delay;
			_repeatCount = repeatCount;
		}
		
		public function reset():void
		{
			stop();
			_currentCount = 0;
		}
		
		public function start():void
		{
			Model.getInstance().timerModel.addTimer(this);
			_lastTime = getTimer();
			_initTime = _lastTime;
			_isStop = false;
			_running = true;
		}
		
		public function stop():void
		{
			Model.getInstance().timerModel.removeTimer(this);
			_isStop = true;
			_running = false;
		}
		
		public function step():void
		{
			var currentTime:int = getTimer();
			var count:int = int((currentTime - _lastTime) / _delay);
			
			if (count >= 1)
			{
				
				for (var i:int =0; i<count; i++)
				{
					if (_isStop)
					{
						return;
					}
					dispatchEvent(new TimerEvent(TimerEvent.TIMER));	
				}
				
				
				_currentCount += count;
				_lastTime = currentTime;
				if ( _repeatCount > 0 && _currentCount >= _repeatCount)
				{
					stop();
					dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE));
				}
			}
		}
		

		public function get delay():int
		{
			return _delay;
		}

		public function set delay(v:int):void
		{
			_delay = v;
		}

		public function get repeatCount():int
		{
			return _repeatCount;
		}

		public function set repeatCount(v:int):void
		{
			_repeatCount = v;
		}

		public function get running():Boolean
		{
			return _running;
		}

		public function get currentCount():int
		{
			return _currentCount;
		}

	}
}